package com.example.shopdemo.utils;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-01-16
 **/
public class SpecificationsBuilder<T> {

    private final List<SearchCriteria> searchCriteriaList;

    public SpecificationsBuilder(){
        this.searchCriteriaList = new ArrayList<>();
    }

    public SpecificationsBuilder with(String key,String operation,Object value){
        searchCriteriaList.add(new SearchCriteria(key,operation,value));
        return this;
    }

    public Specification<T> build(){
        if(searchCriteriaList.size() == 0) {
            return null;
        }

        List<OperationSpecification<T>> specificationList = new ArrayList<>();
        for(SearchCriteria searchCriteria : searchCriteriaList) {
            specificationList.add(new OperationSpecification<T>(searchCriteria));
        }

        Specification<T> result = specificationList.get(0);

        for(int i =1; i < specificationList.size();i++){
            result = Specifications.where(result).and(specificationList.get(i));
        }
        return result;
    }
}
